console.log("Background::this a bg code.");


chrome.runtime.onConnect.addListener((port) =>
{
    console.log("Tab Connect");
    //一个content connect
    let Native_Port: chrome.runtime.Port | null = null;
    let getNativePort: () => chrome.runtime.Port | null = () =>
    {
        if (Native_Port == null)
        {
            Native_Port = chrome.runtime.connectNative('com.lighttool.localfolder');
            Native_Port.onDisconnect.addListener(() =>
            {
                console.log("native::Disconnect");
                Native_Port = null;
            });
            Native_Port.onMessage.addListener((json) =>
            {
                //console.log("native::recv:" + JSON.stringify(json));
                let msgid = json["msgid"] as number;
                port.postMessage(json);
            });
        }
        return Native_Port;
    }

    port.onMessage.addListener((json, inport) =>
    {
        //console.log("Tab::Recv:" + JSON.stringify(json));
        let cmd = json["cmd"];
        var port = getNativePort();
        port?.postMessage(json);
    });
    port.onDisconnect.addListener((inport) =>
    {
        console.log("Tab::Disconnent");
        Native_Port?.disconnect();
    });
});

